/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */
var widthOfBinaryTree = function (root) {
    let res = 0;
    if (!root) {
        return res;
    }
    let arr = [root, 0];
    let head = 0, end = 1;
    while (head != end) {
        let length = end - head;
        let rowend = 0, rowfirst = 0, iffirst = true;
        for (let i = 0; i < length; i++) {
            if (arr[head][0]) {
                arr.push([arr[head][0].left, i * 2]);
                arr.push([arr[head][0].right, i * 2 + 1]);
                rowend = arr[head][1];
                if (iffirst) {
                    rowfirst = arr[head][1];
                    iffirst = false;
                }
            }
            head++;
        }
        res = Math.max(res, rowend - rowfirst + 1);
        end = arr.length;
    }
    return res;
};